﻿using DFGK_WMS.IRepository;
using DFGK_WMS.Model.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace DFGK_WMS.WebAPI
{
    public class OverallException : IAsyncExceptionFilter
    {
        private readonly IErrorLogRepository ierrlog;
        public OverallException(IErrorLogRepository ierrlog)
        {
            this.ierrlog = ierrlog;
        }
        ///全局异常处理
        public Task OnExceptionAsync(ExceptionContext context)
        {
            if (!context.ExceptionHandled)
            {
                //还没处理的异常进来
                var request = context.HttpContext.Request;
                var url = request.Path;
                var queryParams = request.QueryString.ToString();
                //记录日志
                ApiResult result = new ApiResult();
                result.code = "500";
                result.message = "全局异常："+ context.Exception.Message;
                result.data = false;
                result.count = 0;
                context.Result = new JsonResult(result);

                TErrorLog errlog = new TErrorLog();
                errlog.Type = 2;
                errlog.Response = "500";
                errlog.ErrorExcetionMsg = result.message;
                errlog.CreateDate = DateTime.Now;
                errlog.RequestUrl = url;
                errlog.RequestBody = queryParams;
                ierrlog.AddErrorLog(errlog);
                context.ExceptionHandled = true;  //标注下当前这个异常已经处理过了
            }
            return Task.CompletedTask;
        }
    }
}
